package com.ustc.py.learn.service.impl;


import com.ustc.py.learn.constant.KnowledgeTypeEnum;
import com.ustc.py.learn.dao.StudentProgressDao;
import com.ustc.py.learn.service.StudentProgressService;
import com.ustc.py.storage.LoginUserLocalStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class StudentProgressServiceImpl implements StudentProgressService {

    @Autowired
    private StudentProgressDao studentProgressDao;

    /**
     * 根据用户ID和知识类型查询学生的学习进度位图
     *
     * @param userId
     * @param knowledgeType
     * @return
     */
    @Override
    public String getAlgorithmLearningProgress(Long userId, int knowledgeType) {
        return studentProgressDao.queryBitmapByUserIdAndKnowledgeType(userId, knowledgeType);
    }

    /**
     * 根据用户ID和章节ID设置学习状态位图为1
     *  @param userId
     * @param chapterId
     * @return
     */
    // TODO: 使用学习历史纪录替代位图，空间换时间，提升效率 （纯插入新纪录，不去重、不update学习时间）
    @Override
    public void setAlgorithmLearningProgress(Long userId, int chapterId) {
        String bitmap = studentProgressDao.queryBitmapByUserIdAndKnowledgeType(userId, KnowledgeTypeEnum.ALGORITHM.getTypeId());

        // java.lang.NullPointerException临时缓解
        if (bitmap == null) {
            bitmap = "";
        }

        StringBuilder sb = new StringBuilder(bitmap);

        if (chapterId >= bitmap.length()) {
            for (int cnt = 0; cnt < chapterId  + 1 - bitmap.length(); cnt++)
                sb.append("0");
        }
        sb.setCharAt(chapterId, '1');
        String newBitmap =  sb.toString();
        studentProgressDao.setBitmapByUserIdAndKnowledgeType(userId, KnowledgeTypeEnum.ALGORITHM.getTypeId(), newBitmap);
    }

    /**
     * 查询当前登录用户是否学习过某个类别下某章节知识
     *
     * @param knowledgeType
     * @param chapterId
     * @return
     */
    // TODO: 使用学习历史纪录替代位图，空间换时间，提升效率 （纯插入新纪录，不去重、不update学习时间）
    @Override
    public boolean isChapterLearned(int knowledgeType, int chapterId) {
        Long userId = LoginUserLocalStorage.getCurrentLoginUserId();
        String bitmap = this.getAlgorithmLearningProgress(userId, knowledgeType);

        if (bitmap == null || chapterId >= bitmap.length() || bitmap.charAt(chapterId) != '1')
            return false;
        return true;
    }
}
